import {createRouter, createWebHistory} from 'vue-router'


const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            redirect: '/login'
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/components/Login.vue')
        },
        {
            path: '/home',
            name: 'home',
            component: () => import('@/components/Home.vue'),
            redirect: '/welcome',
            children:[
                {
                    path: '/welcome', // 子路由的路径
                    name: 'welcome',
                    component: () => import('@/components/Welcome.vue')
                },
                {
                    path: '/users',
                    name: 'users',
                    component: () => import('@/components/user/Users.vue')
                },
                {
                    path:'/rights',
                    name: 'rights',
                    component: () => import('@/components/power/Rights.vue')
                },
                {
                    path:'/roles',
                    name: 'roles',
                    component :() => import('@/components/power/Roles.vue')
                },
                {
                    path:'/categories',
                    name: 'categories',
                    component :() => import('@/components/goods/Cate.vue')
                }
            ]
        }
    ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const str = sessionStorage.getItem('token')
    const isUnauthorized = !str // 未授权
    // 登录页，直接放行
    if (to.path === '/login') {
        next();
    } else if (isUnauthorized) {
        // 未授权，跳转到登录页
        next('/login')
    } else {
        // 已授权，放行
        next();
    }
})
export default router
